# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'logger'
require 'iconv'
require 'mechanize'

class DospyWater
  
  def initialize(args = {})
    @agent = Mechanize.new
    @forum_code = args[:forum_code]
    @forum_uri = args[:forum_uri]
    @proxy_ip_and_port = args[:proxy_ip_and_port]
  end
  
  def watering
    # **** 初始化
    debug "****  开始在#{@forum_code}:#{@forum_uri}发帖"
    @agent.user_agent_alias = 'Windows IE 7'
    @agent.max_history = 1
    @agent.open_timeout = 10
    if @proxy_ip_and_port.present?
      ip_and_port = @proxy_ip_and_port.split(':')
      @agent.set_proxy(ip_and_port[0],ip_and_port[1].to_i)
      debug "proxy : #{ip_and_port[0]}:#{ip_and_port[1]}"
    end
    # 58.56.108.35:8080
    # 190.41.111.108:8080
    # 187.6.85.12:8080
    #user_name = "嘿嘿_1284109922"
    user_name = "#{@forum_code}_#{timestamp}"
    # **** 注册
    registry user_name
    # **** 登录
#    login user_name
    # **** 发帖
    post_ad
  end

  def registry(user_name)
    debug "**** 注册"
    reg_page = @agent.get('http://bbs.dospy.com/register.php')
    #debug_page_html reg_page
    reg_alert_form = reg_page.form_with(:name => 'bbrules')
    #debug_form reg_alert_form
    reg_page = reg_alert_form.submit(reg_alert_form.button_with( :name => "rulesubmit"))
    #debug_forms reg_page.forms
    reg_form = reg_page.forms.first
    raise_if_no_such_form reg_form, 'register'
    reg_form.set_fields :secanswer => 27,
      :username => user_name,
      :password => '123321',
      :password2 => '123321',
      :email => "mts@gmail.com"
    waiting_to_home_page = reg_form.submit(reg_form.button_with(:name => 'button_with'))
    #debug_page_html waiting_to_home_page
    #debug_page(waiting_to_home_page, 'link')
    waiting_to_home_page.link_with( :href => './').click
    home_page = @agent.get('http://bbs.dospy.com')
    if home_page.links[5].text == user_name
      debug "#{user_name}成功注册"
    else
      raise "#{user_name}注册失败"
    end    
    #debug_page_html waiting_to_home_page
    #debug debug_page(waiting_to_home_page, 'link')
  end

  def login(user_name)
    debug "**** 登录"
    login_page = @agent.get('http://bbs.dospy.com/logging.php?action=login')
    #    debug_page login_page, 'link'
    login_form = login_page.form_with(:name => 'login')
#    debug_form login_form
    login_form.set_fields :username => user_name,
      :password => '123321'
    login_form.button_with(:name => 'loginsubmit').value = 'submit'
    login_success_page = login_form.submit(login_form.button_with(:name => 'loginsubmit'))
    home_page = @agent.get('http://bbs.dospy.com')
    debug "#{home_page.links[5].text}-成功登录"
    #    debug_page home_page, 'link'
    #    debug_page home_page,'link'
#    debug "登录完毕，跳转到 home_page #{home_page.uri}"
  end

  def post_ad
    forum_page = @agent.get('http://bbs.dospy.com').link_with(:href => @forum_uri).click
#    debug forum_page.uri
#    debug_page forum_page, 'link'
    new_post_page = forum_page.link_with(:href => /post.php/ ).click
#    debug new_post_page.uri
#    debug_page new_post_page, 'form'
    new_post_form = new_post_page.forms.first
#    debug "new_post_form's fields: "
#    debug_form new_post_form
    # 开始发帖
    new_post_form['typeid'] = new_post_form.field_with(:name => 'typeid').options[1].value
    new_post_form['secanswer'] = 27
    titles = ['很给力！免费的天气预报短信提醒！','新春贺礼，免费的天气预报、天气预警短信提醒！','懒人必备，免费的天气预报、天气预警短信']
    new_post_form['subject'] = titles[rand(3)]
    new_post_form['message'] = "免费的天气预报短信提醒强力推荐，只要是移动的用户就能申请。目前已升级接口，原先要求提交密码的方式已经取消，采用全新的飞信机器人模式，只需要您同意的飞信加飞信机器人为好友即可。百度上搜索(免费天气预报短信)就可以看到了"
    #new_post_form['subject'] = '觉得给移动赚钱不爽的进来,蹭移动短信去'
   # new_post_form['message'] = "免费的天气预报短信提醒强力推荐，只要是移动的用户就能申请。上百度搜索[/color][/u]： [b]麦吐司 免费天气预报短信[/b]， 利用的是飞信给自己发短信免费的特点。建议给老爸老妈也绑上，一起蹭移动短信。建议给老爸老妈也绑上，一起蹭移动短信。"
    #    new_post_form['message'] = "免费的天气预报短信提醒强力推荐，只要是移动的用户就能申请。上百度搜索[/color][/u]： [b]麦吐司网 天气预报[/b]。 建议给老爸老妈也绑上，一起蹭移动短信。建议给老爸老妈也绑上，一起蹭移动短信。"
    #    new_post_form['subject'] = '1111111111'
    #    new_post_form['message'] = '2222222222'
    new_post_success_page = new_post_form.submit(new_post_form.button_with( :name => "topicsubmit"))
#    debug new_post_success_page.uri
    #debug_page new_post_success_page, 'link'
    debug '发帖结果：'
    debug_page_html new_post_success_page
    #debug_page new_post_success_page,'link'
    debug "**** #{@forum_code}发帖结束"
  end

  def debug(string)
    Logger.new("#{RAILS_ROOT}/log/#{RAILS_ENV}.log").debug string
    puts string
  end

  def debug_page_html(page)
    page.root.search('div.altbg1').each do |body|
      debug gbk_to_utf8(body.inner_html)
    end
  end

  def debug_forms(forms)
    forms.each_with_index do |form,index|
      debug "#{index}. #{form.name}"
    end
  end

  def debug_form(form)
    form.fields.each_with_index do |field,index|
      debug "#{index}. field #{field.name}"
    end
    form.buttons.each_with_index do |button,index|
      debug "#{index}. button #{button.name}"
    end
  end

  def debug_page(page, type = nil)
    case type
    when 'link'
      page.links.each_with_index do |link,index|
        #debug link.node.class.to_s
        debug "link #{index}. is #{link.text} -- #{link.href}"
        #debug "link #{index}. is #{link.node} -- #{link.href}" if link.node.is_a?(Mechanize::Page::Image)
      end
    when 'form'
      page.forms.each_with_index do |form,index|
        #debug form.node.class.to_s
        debug "form #{index}. is -- #{form.action}"
      end
    else
      page.bases.each_with_index do |base,index|
        debug "base #{index}. is -- #{base.text}"
      end
    end
  end

  def raise_if_no_such_form(form,form_name)
    raise "#{@forum_code}-form's name expect: #{form_name} but:#{form.name}" if form.name != form_name
  end

  def raise_if_no_such_page(page,page_uri)
    raise "#{@forum_code}- page's name expect: #{page.uri} but:#{page_uri}" if page.uri != page_uri
  end

  def timestamp
    Time.now.to_i.to_s
  end

  def gbk_to_utf8(gbk_string)
    Iconv.iconv("UTF-8//IGNORE","GBK//IGNORE",gbk_string).to_s
  end
end
